
var requestMode = require('../../js/requestsMode.js');
var session = require('../../js/session.js');
var constants = require('../../js/constants.js');
var model_img_url="../../images/";
var Tools = require('../../js/Tools.js');
var choseList = [];
var menuList = [];
function getWindowSize(){
    var windowWidth=0;
    var windowHeight=0;
    wx.getSystemInfo({
        success: function (res) {
            windowWidth = res.windowWidth;
            windowHeight = res.windowHeight;
        }
    });
    return {
        "windowWidth" : windowWidth,
        "windowHeight" : windowHeight
    }
}
var windowHeight= getWindowSize().windowHeight;
var translaTionY=windowHeight;
var choseListLength=choseList.length;
var tabbarJs = require("../tabbar/tabbar.js");
var init = tabbarJs.init;
var onTabbarItemTap = tabbarJs.onTabbarItemTap;

const PageData={
    data:{
        search_bg : '../../images/search.png',
        joinCar:'../../images/joinCar_now.png',
        sellOut:"../../images/sellOut.png",
        menuList:menuList,
        menuMessage:[],
        choseListLength : choseListLength,
        scrollxWidth : 70*choseListLength,
        activeIndex:'',
        defaultChoseMenu:'',
        'ifShowAlert' :false,
        margin:500,
        toView:'scroll9',
        jhDataForTabbar : Tools.tabBarItems(1,0),
        /*弹窗*/
        choseList : choseList,
        'alertBgShow':'display:none',
        'alertllHeight':windowHeight,
        'alert_transition':'translateY('+translaTionY+'px);transition: all 0s;',
        'close_alertImg':model_img_url+'close_alert.png',
        'sd_img' : model_img_url+ 'details_shopping.png',
        all_price : 0.0,
        'allType' : [],
        'addClick' : false,
        'hasNumber' :1,
        'reduceClick' :false,
        'buttonReduceImg' : model_img_url+'reduce.png',
        'buttonAddImg': model_img_url+'add.png',
        'scrollViewMargin':parseInt(windowHeight) *0.5,
        page:1,
        page_total : 0,
        /*判断是否从首页banner跳转到这*/
        toHereFormIndexBanner : false,
        /*判断从首页分类跳转到这*/
        fromIndexType:false,
        showSearchList:false,
        getSearch:[],
        getSearchLength:0,
        searchPrompt:'搜索关键词如：牛肉、啤酒、餐盒等...',
        cursorImg : model_img_url+'cursor.png',
        closeSearchContent : model_img_url+'redClose.png',
        setCloseBg:'none',
        notShopping:model_img_url+'notOrder.png',
        listLength:0
    },
    /*查询聚焦*/
    inputFocus:function(){
        this.setData({
            showSearchList:true
        })
    },
    tapBody: function () {
        this.setData({
            showSearchList:false
        })
    },
    //查询框变化------------------请求接口获取数据
    searchChange: function (e) {
        let searchContent = e.detail.value;
        let That = this;
        if(searchContent){
            Tools.showLoaddingDefault();
            requestMode.sendRequest('goods/search','POST',{goods_name : searchContent},{}).then(function(success){
                Tools.hideLoaddingToast();
                if(success.data.code == 200){
                    That.setData({
                        getSearch : success.data.data,
                        getSearchLength : success.data.data.length,
                        setCloseBg:'#fff'
                    })
                }else{
                    That.setData({
                        searchPrompt : '暂未搜索到相关商品信息...',
                        getSearch : [],
                        getSearchLength : 0,
                        setCloseBg:''
                    })
                }
            },function(){
                Tools.hideLoaddingToast();
                That.setData({
                    searchPrompt : '暂未搜索到相关商品信息...',
                    getSearch : [],
                    getSearchLength : 0,
                    setCloseBg:''
                })
            })
        }else{
            this.setData({
                showSearchList:false,
                setCloseBg:''
            })
        }
    },
    //关闭查询内容
    closeSearchContent: function () {
        this.setData({
            showSearchList:false,
            setCloseBg:''
        })
    },
    onShow: function () {
        this.setData({
            showSearchList:false,
            setCloseBg:'',
            searchPrompt : '搜索关键词如：牛肉、啤酒、餐盒等...',
            getSearch : [],
            getSearchLength : 0
        })
  /*      wx.setNavigationBarColor({

            frontColor:'#ffffff',

            backgroundColor:'#b50808'

        })*/

    },
    toDetailed: function (e) {
        let goods_id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '../type/detailed/detailed?id='+goods_id
        })
    },
    seeDetailed:function(e){
        let oid= e.currentTarget.dataset.id;
        wx.navigateTo({
            url:"detailed/detailed?id="+oid
        });
    },
    /*出现添加购物车购买弹窗*/
    pf_showAlertForBuy : function() {
        const   This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight,
            'alert_transition':'translateY('+intHeight+'px);transition: all 0s;'
        });
        This.setData({
            alertBgShow:'display:block'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:true
            })
        },10);
        setTimeout(function(){
            This.setData({
                'alert_transition':'translateY('+0+'px);transition: all 0.2s;',
            })
        },10)
    },
    /*弹窗*/
    body_closeAlert:function(){
        const   This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            This.setData({
                alertBgShow:'display:none'
            });
        },300)
    },
    close_alert:function(){
        const   This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            This.setData({
                alertBgShow:'display:none'
            });
        },300)
    },
    choseThisType:function(e){
        var clickIndex=e.currentTarget.dataset.index;
        const allType=this.data.allType;
        for(var i=0;i<allType.length;i++){
            if(i==clickIndex){
                allType[i].class='chose';
            }else{
                allType[i].class='notChose';
            }
        }
        this.setData({
            'allType':allType
        });
        this.reloadPrice();
    },
    ///获取当前选中商品对应规格的价格
    getCurrentPerPrice : function () {
        const allType=this.data.allType;
        var currentPrice = 0.0;
        for(var i=0;i<allType.length;i++){
            if(allType[i].class == 'chose'){
                return allType[i].space_price;
            }
        }
    },
    ///刷新弹窗价格
    reloadPrice : function () {
        var  perPrice = this.getCurrentPerPrice();
        var   totalPrice = this.data.hasNumber * perPrice;
        this.setData(
            {
                all_price : totalPrice.toFixed(2)
            }
        );
    },
    tap_add:function(){
        const This=this;
        This.setData({
            addClick:true
        });
        if(This.data.hasNumber>=1){
            This.setData({
                hasNumber:parseInt(This.data.hasNumber)+1
            });
            this.reloadPrice();
        }
        setTimeout(function(){
            This.setData({
                addClick:false
            });
        },200)
    },
    numberChange:function(e){
        const  This=this;
        This.setData({
            hasNumber:e.detail.value
        });
        this.reloadPrice();
    },
    tap_reduce:function(){
        if (this.data.hasNumber <= 1)
        {
            return;
        }
        let This=this;
        this.setData({
            reduceClick:true
        });
        if(this.data.hasNumber>1){
            This.setData({
                hasNumber:parseInt(This.data.hasNumber)-1
            });
            this.reloadPrice();
        }
        setTimeout(function(){
            This.setData({
                reduceClick:false
            });
        },200)
    },
    settingJoinCar:function(e){
        const   This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        var space_id = "";
        for (var tempIndex = 0;tempIndex < this.data.allType.length;tempIndex++) {
            if(this.data.allType[tempIndex].class == 'chose')
            {
                //找到对应选中的那个规格
                space_id = this.data.allType[tempIndex].space_id;
                break;
            }
        }
        let that = this;
        Tools.showLoaddingDefault();
        ///网络请求加入购物车
        requestMode.sendRequest("shop-cart/add","POST",{goods_id:this.data.chooseShopId,number:this.data.hasNumber,space_id:space_id},{skey:session.get('sKey')}).then(
            function (sucessRes)
            {
                that.closeBuyAlertView();
                Tools.hideLoaddingToast();
                let responseCode = sucessRes.data.code;
                if(responseCode == 200)
                {
                    ///加入购物车成功
                    ///给购物车数量加1
                    getApp().buyCarCount += 1;
                    ///重新刷新tab上面的数量
                    Tools.requestBuyCarCount(false,that,1);
                    Tools.showSuccessInfoToast("已添加进购物车");
                }else
                {
                    ///加入购物车失败
                    Tools.showErrorToast(sucessRes.data.message);
                }

            },function(wrongNetRes)
            {
                Tools.showWrongNetWorkToast();
                that.closeBuyAlertView();
            }
        );

    },
    closeBuyAlertView: function() {
        let that = this;
        setTimeout(function(){
            that.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            that.setData({
                alertBgShow:'display:none'
            });
        },300);
    },
    onTabbarItemTap:onTabbarItemTap,
    getShoppingList:function(id,page,size){
        let This = this;
        let ShoppingList = [];
        let sKey = session.get('sKey');
        Tools.showLoaddingDefault();
        This.setData({
            listLength : 0,
        });
        requestMode.sendRequest('goods/list','POST',{page:page,size:size,goods_type_id:id},{sKey:sKey}).then(function(res){
            let code = res.data.code;
            if(code == 200){
                This.setData({
                        page_total : res.data.data.page_total
                    }
                );
                ShoppingList = res.data.data.list;
                var newMenuMessage = This.data.menuMessage;
                /*   if(newMenuMessage.length!=0){
                 delete newMenuMessage[newMenuMessage.length-1].margin;
                 }*/
                ShoppingList.forEach(function(value){
                    if(value['total_stock'] == 0 ){
                        value.sellOut = true;
                    }else{
                        value.sellOut = false;
                    }
                    value.message = value.name;
                    newMenuMessage.push(value);
                });
                This.setData({
                    menuMessage : newMenuMessage,
                    listLength : newMenuMessage.length,
                    page:page
                });
                Tools.hideLoaddingToast();
            }else{
                Tools.showErrorToast(res.data.message);
            }
        },function(){
            Tools.showWrongNetWorkToast();
        });
    },

    ///获取分类列表
    getSonList:function(id){
        let This = this;
        let getTypeList=[];
        let defaultChoseMenu = This.data.defaultChoseMenu;
        let toHereFormIndexBanner = This.data.toHereFormIndexBanner;
        This.setData({
            listLength : 0,
        });
        requestMode.sendRequest('goods/types','POST',{pid:id},{}).then(function(res){
            let code = res.data.code;
            if(code == 200){
                getTypeList = res.data.data.list;
                let page = This.data.page;
                if(This.data.fromIndexType == true){
                    defaultChoseMenu = getTypeList[0].id
                }
                if( toHereFormIndexBanner == true){
                    getTypeList.forEach(function (v) {
                        if(v['id'] == defaultChoseMenu){
                            v['active'] = true;
                            This.setData({
                                toHereFormIndexBanner: false,
                                menuList:getTypeList,
                                defaultChoseMenu:v['id'],
                                page : 1
                            });
                            This.getShoppingList(v['id'],page,constants.size)
                        }
                    });
                }else{
                    getTypeList[0].active = true;
                    This.setData({
                        menuList:getTypeList,
                        defaultChoseMenu:getTypeList[0].id,
                        page : 1
                    });
                    This.getShoppingList(getTypeList[0].id,page,constants.size)
                }
            } else{
                Tools.showErrorToast(res.data.message);
            }
        },function(res){
            Tools.showWrongNetWorkToast();
        })
    },
    getTopMenu:function(id){
        let getTypeList =[];
        let This =  this;
        let activeIndex = This.data.activeIndex;
        let toHereFormIndexBanner = This.data.toHereFormIndexBanner;
        requestMode.sendRequest('goods/types','POST',{pid:id},{}).then(function(res){
            let code = res.data.code;
            if(code == 200){
                getTypeList = res.data.data.list;
                if(toHereFormIndexBanner == true){
                    This.getSonList(activeIndex);
                    This.setData({
                        choseList:getTypeList,
                        choseListLength:getTypeList.length,
                        activeIndex:activeIndex
                    });
                }else{
                    This.setData({
                        choseList:getTypeList,
                        choseListLength:getTypeList.length,
                        activeIndex:getTypeList[0].id
                    });
                    This.getSonList(getTypeList[0].id);
                }
            } else{
                Tools.showErrorToast(res.data.message);
            }
        },function(){
            Tools.showWrongNetWorkToast();
        })
    },
    onLoad:function(res){
        Tools.requestBuyCarCount(false,this,1);
        let This = this;
        let defaultTopMenuId = res.goods_type_pid;
        let defaultCenterId = res.goods_type_id;
        if(defaultTopMenuId){
            This.setData({
                activeIndex : defaultTopMenuId,
                defaultChoseMenu : defaultCenterId,
                toHereFormIndexBanner : true
            })
        }
        /*判断是否从首页分类跳转到这*/
        let fromIndexType = res.fromIndexType;
        if(fromIndexType){
            This.setData({
                fromIndexType : true
            })
        }
        This.getTopMenu(0)
    },
    choseTheType:function(e){
        const This = this;
        if(This.data.activeIndex != e.currentTarget.dataset.id){
            This.setData({
                activeIndex : e.currentTarget.dataset.id,
                page:1,
                menuMessage:[]
            });
            This.getSonList(e.currentTarget.dataset.id);
        }
    },
    choseMenu:function(e){
        const This = this;
        This.setData({
            defaultChoseMenu : e.currentTarget.dataset.id,
            page:1,
            menuMessage:[]
        });
        Tools.showLoaddingDefault();
        This.getShoppingList(e.currentTarget.dataset.id,(This.data.page),constants.size)
    },

    /*   onPullDownRefresh: function() {
     let This = this;
     This.setData({
     page:0,
     menuMessage:[]
     });
     This.getShoppingList(This.data.defaultChoseMenu,parseInt(This.data.page)+1,constants.size);
     },*/
    toBottom:function(){
        if (this.data.page >= this.data.page_total) {
            return;
        }
        var  currentPage = this.data.page;
        this.setData({
                page : currentPage + 1
            });
        let This = this;
        This.getShoppingList(This.data.defaultChoseMenu,parseInt(This.data.page),constants.size);
    },
    joinCarTheOne:function(e){
        let that = this;
        let data =this.data.menuMessage;
        let id = e.currentTarget.dataset.id;
        let item = e.currentTarget.dataset.item;
        this.setData({
                currentSelectItem : item
            });
        ///请求商品详细信息
        Tools.showLoaddingDefault();
        requestMode.sendRequest("goods/detail","POST",{goods_id:id},{skey:session.get("sKey")}).then(
            function(sucessRes) {
                Tools.hideLoaddingToast();
                let responseCode = sucessRes.data.code;
                if(responseCode == 200) {
                    //请求成功
                    let detailModel = sucessRes.data.data;
                    for (let tempIndex = 0;tempIndex < detailModel.space.length; tempIndex++) {
                        if (tempIndex == 0) {
                            detailModel.space[tempIndex].class = "chose";
                        }else {
                            detailModel.space[tempIndex].class = "notChose";
                        }
                    }
                    if (detailModel.space.length)
                    {
                        that.setData(
                            {
                                all_price : detailModel.space[0].space_price
                            }
                        );
                    }
                    that.setData({
                            sd_img : detailModel.img,
                            allType : detailModel.space,
                            chooseShopId : detailModel.id,
                            chooseShopStock : detailModel.stock,
                            chooseShopName : detailModel.name,
                            windowData:detailModel
                        }
                    );
                    that.pf_showAlertForBuy();
                }else {
                    ///网络请求失败

                    Tools.showErrorToast(sucessRes.data.message);
                }
            },function(wrongNetRes) {
                Tools.showWrongNetWorkToast();
            }
        );
    },
    submit:function(e){
        let This = this;
        if(This.data.hasNumber == 0 || This.data.hasNumber==''){
            This.setData({
                hasNumber:1
            });
            Tools.showErrorToast('数量最少为一')
        }else{
            let currentSelectShop = This.data.windowData;
            currentSelectShop['number'] = parseInt(This.data.hasNumber);//商品数量
            for (var tempIndex = 0;tempIndex < This.data.allType.length;tempIndex++) {
                if(This.data.allType[tempIndex].class == 'chose') {
                    //找到对应选中的那个规格
                    currentSelectShop["space_id"] = This.data.allType[tempIndex].space_id;
                    currentSelectShop["space_price"] = This.data.allType[tempIndex].space_price;
                    currentSelectShop["space_name"] = This.data.allType[tempIndex].space_name;
                    currentSelectShop["space_unit"] = This.data.allType[tempIndex].space_unit;
                    currentSelectShop["space_stock"] = This.data.allType[tempIndex].space_stock;
                    currentSelectShop["space_sold"] = This.data.allType[tempIndex].space_sold;
                    currentSelectShop['goods_id'] = This.data.chooseShopId;
                    break;
                }
            }
            if(currentSelectShop['detail']){
                delete currentSelectShop['detail'];
            }
            let data=[currentSelectShop];
            wx.navigateTo({
                url:'../mines/confirmationOrder/confirmationOrder?shopArray='+JSON.stringify(data)+'&shop_cart_ids='
            })
        }
    }
};
init(PageData);